package org.jetlinks.pro.clickhouse.configuration;

import org.jetlinks.core.device.DeviceRegistry;
import org.jetlinks.pro.clickhouse.ClickHouseOperations;
import org.jetlinks.pro.clickhouse.ClickHouseProperties;
import org.jetlinks.pro.clickhouse.RestfulClickHouseOperations;
import org.jetlinks.pro.clickhouse.device.ClickHouseDeviceDataStoragePolicy;
import org.jetlinks.pro.device.service.data.DeviceDataStoragePolicy;
import org.jetlinks.pro.device.service.data.DeviceDataStorageProperties;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties(ClickHouseProperties.class)
@ConditionalOnProperty(prefix = "clickhouse", value = "enabled", havingValue = "true")
public class ClickHouseConfiguration {


    @Bean(destroyMethod = "destroy")
    public RestfulClickHouseOperations clickHouseOperations(ClickHouseProperties properties) {
        return new RestfulClickHouseOperations(properties);
    }

    @Configuration(proxyBeanMethods = false)
    @ConditionalOnClass(DeviceDataStoragePolicy.class)
    @ConditionalOnProperty(prefix = "clickhouse", value = "enabled", havingValue = "true")
    static class ClickHouseDeviceDataStoragePolicyConfiguration {
        @Bean
        @ConfigurationProperties(prefix = "jetlinks.device.storage.clickhouse")
        public ClickHouseDeviceDataStoragePolicy clickHouseDeviceDataStoragePolicy(ClickHouseOperations operations,
                                                                         DeviceRegistry registry,
                                                                         DeviceDataStorageProperties properties,
                                                                         ClickHouseProperties clickHouseProperties) {
            return new ClickHouseDeviceDataStoragePolicy(operations, registry, properties, clickHouseProperties);
        }
    }
}
